package com.lsp.server.product.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsp.server.common.Apiresponse;
import com.lsp.server.product.domain.po.*;
import com.lsp.server.product.domain.vo.AttrVo;
import com.lsp.server.product.mapper.ShopMapper;
import com.lsp.server.product.mapper.TypeMapper;
import com.lsp.server.utils.TablePageData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @ClassName ShopService
 * @Description 商品管理业务层
 * @Author Mr Hao
 * @Date 2021/11/25 14:37
 */
@Service
@Transactional
public class ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private TypeMapper typeMapper;

    private  StringBuffer sb=null;

    public List<Map> queryAllDataStr() {
        List<Map> rs=new ArrayList<>(); // 返回的数据

        //先得到所有的分类数据
        List<ProductType> types = typeMapper.queryAllData();
        //遍历所有的数据
        for (ProductType t :types) {
            //判断t是否为父节点
            boolean parent = isParent(t.getId(), types);
            if(parent==false){
                Map m=new HashMap();
                m.put("id",t.getId());
                sb=new StringBuffer(t.getName());
                getCildrenName(t.getPid(),types);

                m.put("name",getRevertStr(sb));
                rs.add(m);
            }
        }
        return rs;
    }
    private String getRevertStr(StringBuffer sb){
        StringBuffer str=new StringBuffer();
        // 789/456/123
        String[] split = sb.toString().split("/");
        List<String> strings = Arrays.asList(split);
        Collections.reverse(strings);
        for(String t :strings){
            str.append(t).append("/");
        }
        return str.substring(0,str.length()-1).toString();

    }
    /*   id 父节点name 拼到sb  */
    private void getCildrenName(Integer pid,List<ProductType> datas){
        for (int i = 0; i <datas.size() ; i++) {
            ProductType type = datas.get(i);
            if(type.getId().equals(pid)){
                sb.append("/").append(type.getName());
                if(!type.getPid().equals(0)){
                    getCildrenName(type.getPid(),datas);
                }
                break;
            }
        }
    }

    /*
     * 判断当前id 是否有子节点 */
    private boolean isParent(Integer id,List<ProductType> datas){
        for (ProductType t :datas) {
            if(t.getPid().equals(id)){
                return true;
            }
        }
        return false;
    }

    /*   拼接  type数据中的   ,children:[]   */
    private void getCildren(ProductType type,List<ProductType> datas){
        sb.append(",\"children\":").append("[");
        boolean flag=false;
        for (ProductType t:datas) {
            //判断当前数据是否为当前节点的子节点
            if(t.getPid().equals(type.getId())){
                sb.append("{\"id\":").append(t.getId()).append(",\"pid\":").append(t.getPid()).append(",\"label\":\"").append(t.getName()).append("\"");
                getCildren(t,datas);
                sb.append("},");
                flag=true;
            }
        }
        // 判断去掉多余的逗号  还是去掉children    sb 当前就是 ,children:[{},{},
        if(flag){ //去逗号
            sb.replace(sb.length()-1,sb.length(),"]");
        }else{ // ,children:[
            sb.replace(sb.length()-13,sb.length(),"");
        }
    }

    /**
     *
     * @param tid
     * @return
     */
    public Map getAttrValues(Integer tid) {
        //构建返回值
        Map map = new HashMap();
        List<AttrVo> skuData = new ArrayList<>();
        List<AttrVo> attrData = new ArrayList<>();

        List<AttrVo> attrs = typeMapper.getAttrValues(tid);
            //遍历所有属性数据  完善值数据
            for (int i = 0; i<attrs.size(); i++){
                AttrVo attr = attrs.get(i);
                // 根据属性id 查询值
                List<ProductAttrValues> productAttrValues = typeMapper.queryAllValues(attr.getId());
                //设置默认值
                if(attr.getTypes().equals(2)){
                    attr.setVals(new ArrayList<>());
                }else{
                    attr.setVals("");
                }
                attr.setValues(productAttrValues);

                if (attr.getIsSku()==0){
                    attrData.add(attr);
                }else {
                    skuData.add(attr);
                }
            }
            map.put("skuData",skuData);
            map.put("attrData",attrData);
            return map;
    }

    /**
     * 新增
     * @param shop
     * @param valuess
     */
    public void addShop(ProductShop shop, String valuess,String imgs) {
        shopMapper.addShop(shop);
        //处理json数组
        JSONArray array = JSON.parseArray(valuess);
        //声明list对象
        List<ProductSp> list = new ArrayList<>();
        //遍历json数组
        for (int i=0;i<array.size();i++){
            //json对象
            JSONObject obj = (JSONObject) array.get(i);
            //声明ProductSp
            ProductSp productSp = new ProductSp();
            productSp.setPid(shop.getId());
            productSp.setValuess(obj.toString());
            list.add(productSp);
        }
        shopMapper.addValues(list);
        //处理json数组
        JSONArray arr = JSON.parseArray(imgs);
        //声明list对象
        List<ProductShopImg> imgs1 = new ArrayList<>();
        //遍历json数组
        for (int i=0;i<arr.size();i++){
            //json对象
            JSONObject o = (JSONObject) arr.get(i);
            //声明ProductSp
            ProductShopImg psi = new ProductShopImg();
            psi.setPid(shop.getId());
            psi.setImgs(o.getString("url"));
            psi.setName(o.getString("name"));
            imgs1.add(psi);
        }
        shopMapper.addImgs(imgs1);
    }

    /**
     * 查询
     * @param map
     * @return
     */
    public TablePageData queryList(Map map) {
        return new TablePageData(shopMapper.queryCount(map),shopMapper.queryList(map));
    }

    /**
     * 查询附图
     * @param id
     * @return
     */
    public Object imgList(Integer id) {
        List<ProductShopImg> list = shopMapper.imgList(id);
        return list;
    }

    /**
     * 查询回显数据
     * @param pid
     * @return
     */
    public Map queryShopValuesByPid(Integer pid) {
        Map rs=new HashMap(); //skudata attrdata
        JSONObject attrData=null;
        List<JSONObject> skuData=new ArrayList<>();
        //查询所有的数据
        List<String> shopValues = shopMapper.queryValuesByPid(pid);
        for (int i = 0; i <shopValues.size() ; i++) {
            JSONObject parse = (JSONObject) JSONObject.parse(shopValues.get(i));
            Object count = parse.get("count");
            if(count!=null){
                skuData.add(parse);
            }else{
                attrData=parse;
            }
        }

        rs.put("sd",skuData);
        rs.put("ad",attrData);

        return rs;
    }

    public void updateValuesByPid(Integer pid, String values) {
        shopMapper.delValuesByPid(pid);
        //处理json数组    fastjson   阿里
        JSONArray objects = JSONArray.parseArray(values);
        //声明list对象
        List<ProductSp> list=new Vector<>();
        //遍历json数组
        for (int i = 0; i <objects.size() ; i++) {
            //json对象
            JSONObject o = (JSONObject) objects.get(i);
            //声明shopvalue
            ProductSp v=new ProductSp();
            v.setValuess(o.toJSONString());
            v.setPid(pid);
            list.add(v);
        }
        shopMapper.addValues(list);
    }
}